#!/usr/bin/env python3
# coding=utf-8
"""
Python 3.14 多线程性能测试 - CPU密集型任务
测试GIL移除后的多线程性能提升
"""

import threading
import time
import multiprocessing
import concurrent.futures
from typing import List
import sys


def cpu_intensive_task(n: int) -> int:
    """
    模拟CPU密集型任务 - 计算平方和
    
    参数:
        n (int): 计算次数
    
    返回:
        int: 计算结果
    """
    result = 0
    for i in range(n):
        result += i * i
    return result


def single_thread_test(n: int) -> float:
    """单线程测试"""
    start_time = time.time()
    result = cpu_intensive_task(n)
    end_time = time.time()
    print(f"单线程结果: {result}, 耗时: {end_time - start_time:.4f} 秒")
    return end_time - start_time


def multi_thread_test(num_threads: int, n: int) -> float:
    """多线程测试"""
    start_time = time.time()
    
    threads = []
    for _ in range(num_threads):
        thread = threading.Thread(target=cpu_intensive_task, args=(n,))
        threads.append(thread)
        thread.start()
    
    for thread in threads:
        thread.join()
    
    end_time = time.time()
    print(f"{num_threads}线程耗时: {end_time - start_time:.4f} 秒")
    return end_time - start_time


def thread_pool_test(num_threads: int, n: int) -> float:
    """线程池测试"""
    start_time = time.time()
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
        futures = [executor.submit(cpu_intensive_task, n) for _ in range(num_threads)]
        results = [future.result() for future in futures]
    
    end_time = time.time()
    print(f"线程池({num_threads}线程)耗时: {end_time - start_time:.4f} 秒")
    return end_time - start_time


def process_pool_test(num_processes: int, n: int) -> float:
    """进程池测试（对比）"""
    start_time = time.time()
    
    with concurrent.futures.ProcessPoolExecutor(max_workers=num_processes) as executor:
        futures = [executor.submit(cpu_intensive_task, n) for _ in range(num_processes)]
        results = [future.result() for future in futures]
    
    end_time = time.time()
    print(f"进程池({num_processes}进程)耗时: {end_time - start_time:.4f} 秒")
    return end_time - start_time


def performance_comparison():
    """性能对比测试"""
    print("=== Python 3.14 多线程性能测试 ===")
    print(f"CPU核心数: {multiprocessing.cpu_count()}")
    print()
    
    # 测试参数
    n = 5 * 10**6  # 计算次数
    num_threads = multiprocessing.cpu_count()
    
    # 单线程测试
    print("1. 单线程测试:")
    single_time = single_thread_test(n)
    
    print("\n2. 多线程测试:")
    multi_time = multi_thread_test(num_threads, n)
    
    print("\n3. 线程池测试:")
    pool_time = thread_pool_test(num_threads, n)
    
    print("\n4. 进程池测试（对比）:")
    process_time = process_pool_test(num_threads, n)
    
    # 性能提升分析
    print("\n=== 性能分析 ===")
    print(f"多线程加速比: {single_time / multi_time:.2f}x")
    print(f"线程池加速比: {single_time / pool_time:.2f}x")
    print(f"进程池加速比: {single_time / process_time:.2f}x")
    
    if multi_time < single_time:
        print("✅ 多线程性能提升明显！")
    else:
        print("⚠️  多线程性能未提升，可能需要启用自由线程模式")


if __name__ == "__main__":
    print("Python 3.14 多线程性能测试 - CPU密集型任务")
    print("Python 版本:", sys.version)
    print("gil enabled:", sys._is_gil_enabled())

    performance_comparison()